package com.seahorse.youliao.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.seahorse.youliao.common.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ProjectName: youliao
 * @Package: com.seahorse.youliao.security
 * @ClassName: MyAccessDeniedHandler
 * @Description: 认证异常处理器
 * @author:songqiang
 * @Date:2020-11-25 16:22
 **/
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest resq, HttpServletResponse resp, AccessDeniedException exception) throws IOException, ServletException {
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        ResponseEntity respBean = ResponseEntity.error("无权限：" + exception.getMessage());
        String json = JSONObject.toJSONString(respBean);
        out.write(json);
        out.flush();
        out.close();
    }
}
